// pages/list/list.js
//获取应用实例
const app = getApp();
const api = require('../../utils/api');
const constant = require('../../utils/constant');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    //获取全局变量 导航栏的高度statusBarHeight
    statusBarHeight: app.globalData.statusBarHeight,
    // 胶囊
    jiaonang: app.globalData.jiaonang, 
    navigationHeight: app.globalData.navigationHeight,
    // 底部菜单高度
    tabbarHeight: app.globalData.tabbarHeight,
    BASEURLWWW:constant.BASEURLWWW,
    // search高度
    searchHeight: 0,
    // screen高度
    screenHeight: 0,
    // screenMore高度
    screenMoreHeight: 0,
    isScreenMoreShow: false,
    // 搜索关键词
    keyword: '',
    // 商品列表
    goodsList: [],
    // 无数据提示
    noDataNotice:'',
    noDataNoticeStatus: false,
    // 分页
    pagination:{
      pageNum: 1,  //分页初始值，页号1
      pageSize: 10, //分页初始值，每页20条
      total: null
    },
    // 是否是商品圈商品
    isFriend: false,
    friend: {},
    // 返回顶部
    floorstatus: false,
    topNum:0,
    // 筛选条件,sales_sum:销量 shop_price:价格 views_sum:浏览量||DESC:从大到小,ASC:从小到大，
    screen:{
      orderK: '',
      orderV: '',
      name: '',
      brand_id: null,
      condition_item_id:[]
    },
    // 购物车数量
    carNum: 0,
    // 酒分类名字
    typeItemName: '选酒分类',
    // 一级分类数据
    faterTypeListData: [],
    // 分类下拉菜单
    isTypeDownShow: false,
    // 条件是不是分类
    isType: false,
    // 分类id
    typeId:[],
    // 侧边筛选
    isSideScreenShow: false,
    // 品牌数据
    brandListData: [],
    // 品牌样式id
    brandStyleId: null,
    brandStyle: 'down',
    // 筛选条件数据
    screenListData: [],
    // 筛选条件样式id
    screenStyleId: null,
    screenStyle: 'down',
    // 筛选条件：品牌检索
    brandSearch: 'all'
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this;
    let query = wx.createSelectorQuery();
    // 获取搜索板块高度
    query.select('#search').boundingClientRect(rect=>{  
      that.setData({
        searchHeight: rect.height
      })
    }).exec();
    // 获取筛选高度
    query.select('#screen').boundingClientRect(rect=>{  
      that.setData({
        screenHeight: rect.height
      })
    }).exec();
    
    // 获取购物车数量
    this.getCarListData();
    // 商品圈搜索
    if(options.friend){
      let friend = JSON.parse(options.friend);
      this.getFriendGoodsListData(friend,this.data.pagination,this.data.screen);
      this.setData({
        isFriend: true,
        friend,
        keyword: friend.frend_title
      })
      return false;
    }
    // 关键词搜索
    if(options.keyword){
      this.setData({
        keyword: options.keyword,
        isFriend: false,
        frendId: null,
        'screen.name': options.keyword
      })
      this.getGoodsListData(this.data.pagination,this.data.screen);
      return false;
    }
    // 分类搜索
    if(options.typename){
      let typeName = options.typename;
      let typeScreen = JSON.parse(options.screen);
      let nowScreen = {...this.data.screen,...typeScreen};

      that.setData({
        isScreenMoreShow: true,
        keyword: typeName,
        isFriend: false,
        frendId: null,
        isType: true,
        typeId: nowScreen.goods_category_id,
        typeItemName: typeName,
        screen:nowScreen
      })
      this.getGoodsListData(this.data.pagination,this.data.screen);
      this.getBrandListAndScreenList();
      return false;
    }
    
    this.setData({
      isFriend: false,
      frendId: null
    })
    this.getGoodsListData(this.data.pagination,this.data.screen);
  },
  // 获取购物车列表数据
  getCarListData:function(){
    api.carList([]).then(res => {
      if(res.code == 0){
        this.setData({
          carNum: res.data.data.length
        })
      }
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  // 点击搜索框
  jumpToSearch: function() {
    wx.navigateTo({
      url: '/pages/search/search'
    })
   },
   // 返回到首页
  back:function(){
    wx.reLaunch({
      url: '/pages/index/index'
    })
  },
  // 跳转到购物车
  jumpToCar:function(){
    wx.reLaunch({
      url: '/pages/car/car'
    })
  },
  // 回到顶部显示
  goToTopShow:function(e){
    if (e.detail.scrollTop > 500) {
      this.setData({
        floorstatus: true
      });
    } else {
      this.setData({
        floorstatus: false
      });
    }
  },
  //回到顶部
  goTop: function (e) {  // 一键回到顶部
    this.setData({
      topNum:0
    })
  },
  // 删除关键词
  deleteKeyword:function(){
      this.setData({
        keyword: '',
        typeItemName: '酒分类',
        isType: false,
        typeId: [],
        isSideScreenShow: false,
        noDataNoticeStatus: false,
        goodsList: [],
        'screen.goods_category_id': [],
        'pagination.pageNum': 1,
        'pagination.pageSize': 10,
        'pagination.total': null,
        isFriend: false,
        frendId: null,
      })
    this.getGoodsListData('',this.data.pagination,this.data.screen);
  },
  // 带着关键词到搜索界面
  jumpToSearchWithKeyword:function(){
    wx.navigateTo({
      url: '/pages/search/search?keyword='+ this.data.keyword
    })
  },
  // 条件筛选
  screenHandle:function(e){
    let screenType = e.currentTarget.dataset.type;
    let nowScreen = this.data.screen;
    let screen = {
      orderK: '',
      orderV: ''
    }
    // 筛选类型
    if(screenType == 'default'){
      nowScreen.orderK = ''
      nowScreen.orderV = ''
    }else{
      nowScreen.orderK = screenType;
      if(screenType == nowScreen.orderK){
        // 筛选条件切换
        if(nowScreen.orderV == ''){
          nowScreen.orderV = 'DESC';
        }else if(nowScreen.orderV == 'DESC'){
          nowScreen.orderV = 'ASC';
        }else{
          nowScreen.orderV = '';
        }
      }else{
        nowScreen.orderV = 'DESC';
      }
      
    }
    // 更新筛选条件
    this.setData({
      screen:nowScreen,
      goodsList: [],
      'pagination.pageNum': 1,
      'pagination.pageSize': 10,
      'pagination.total': null,
    })

    if(this.data.isFriend){ // 是商品圈商品
      this.getFriendGoodsListData(this.data.friend,this.data.pagination,this.data.screen);
    }else{ // 商品列表
      this.getGoodsListData(this.data.pagination,this.data.screen);
    }
  },
  // 获取商品列表数据
  getGoodsListData:function(pagiantion,screen,reset){
    let goodsListArr = this.data.goodsList;
    // 数据已经到底
    if(goodsListArr.length == this.data.pagination.total){
      wx.showToast({
        title: '已经没有了~',
        icon: 'none',
        duration: 1500
      })
    }else{
      api.search(pagiantion,screen).then(res => {
        if(res.code == 0){
          if(res.data.total != 0){
            goodsListArr.push(...res.data.list);
            if(reset == true){
              if(this.data.typeId!=null && this.data.typeId.length>0){
                this.setData({
                  isType: true,
                  goodsList: goodsListArr,
                  'pagination.total': res.data.total,
                })
              }else{
                this.setData({
                  isType: false,
                  goodsList: goodsListArr,
                  'pagination.total': res.data.total,
                })
              }
            }else{
              // 有数据，并且选择了分类
              if(this.data.typeId!=null && this.data.typeId.length>0){
                this.setData({
                  isType: true,
                  goodsList: goodsListArr,
                  'pagination.total': res.data.total,
                  noDataNoticeStatus: false
                })
              }else{
                this.setData({
                  isType: false,
                  goodsList: goodsListArr,
                  'pagination.total': res.data.total,
                  noDataNoticeStatus: false
                })
              }
            } 
          }else{
              this.setData({
                isType: false,
                goodsList: [],
                screen: {orderK: '',orderV: ''},
                noDataNotice: this.data.keyword,
                noDataNoticeStatus: true
              })
            this.getGoodsListData(pagiantion,this.data.screen,true);
          }
        }else{
          wx.showToast({
            title: res.msg,
            icon: 'none',
            duration: 1500
          })
        }
      })
    }
    
  },
  // 获取商品圈商品
  getFriendGoodsListData:function(friend,pagination,screen){
    let goodsListArr = this.data.goodsList;
    // 数据已经到底
    if( goodsListArr.length == this.data.pagination.total){
      wx.showToast({
        title: '已经没有了~',
        icon: 'none',
        duration: 1500
      })
    }else{
      api.friendGoods(friend.friend_id,pagination,screen).then(res => {
        if(res.code == 0){
          if(res.data.total != 0){
            goodsListArr.push(...res.data.list);
            this.setData({
              goodsList: goodsListArr,
              'pagination.total': res.data.total,
              keyword: friend.friend_title
            })
          }else{
            this.setData({
              'screen.goods_category_id':[],
              keyword: friend.friend_title,
              noDataNotice: friend.friend_title,
              noDataNoticeStatus: true
            })
            this.getGoodsListData(pagination,screen);
          }
        }else{
          wx.showToast({
            title: res.msg,
            icon: 'none',
            duration: 1500
          })
        }
      })
    }
    
  },
  // 滚动到底部
  bindscrolltolower:function(){
    let newPageNum = this.data.pagination.pageNum + 1;
    this.setData({
      'pagination.pageNum': newPageNum
    })
    if(this.data.isFriend){
      this.getFriendGoodsListData(this.data.friend,this.data.pagination,this.data.screen);
    }else{
      this.getGoodsListData(this.data.pagination,this.data.screen);
    }
    
  },
  // 点击商品跳转到商品详情页
  jumpToGoods:function(e){
    let goodsId = e.currentTarget.dataset.goodsid;
    wx.navigateTo({
      url: '/pages/goods/goods?goods_id='+goodsId
    })
  },
  // 背景不滚动
  dontMove: function(){
    return;
  },
  // 显示分类下拉菜单
  showTypeDown:function(){
    api.getFatherTypeList().then(res=>{
      if(res.code == 0){
        this.setData({
          faterTypeListData: res.data,
          isTypeDownShow: true
        })
      }
      
    })
  },
  // 根据分类id获取商品列表
  getTypeGoods:function(e){
    let item = e.currentTarget.dataset.item;
    this.setData({
      typeId: [item.goods_category_id],
      typeItemName: item.name,
      goodsList: [],
      'screen.goods_category_extend_id': [],
      'screen.goods_category_id':[item.goods_category_id],
      keyword:item.name,
      isTypeDownShow: false,
      'pagination.pageNum': 1
    })
    this.getGoodsListData(this.data.pagination,this.data.screen);
    this.getBrandListAndScreenList();
  },
  // 通过分类id，获取筛选条件和品牌数据
  getBrandListAndScreenList:function(){
    if(this.data.typeId!=null && this.data.typeId.length>0){
      // 品牌列表
      api.getBrandList(this.data.typeId).then(res => {
        if(res.code == 0){
          res.data.forEach(item => {
            item.choose = false;
            item.childrens.forEach(node => {
              node.choose = false;
            })
          })
          this.setData({
            brandListData: [res.data[0]]
          })
        }
      })
      // 筛选条件数据
      api.getScreenList(this.data.typeId).then(res => {
        if(res.code == 0){
          let i = 0;
          res.data.forEach(item => {
            i++;
            item.id = i;
            item.choose = false;
            item.condition_item.forEach(node => {
              i++
              node.choose = false;
              node.id = i;
            })
          })
          this.setData({
            screenListData: res.data
          })
        }
      })
    }
  },
  // 关闭分类下拉菜单
  closeTypeDown:function(){
    this.setData({
      isTypeDownShow: false
    })
  },
  // 显示侧边筛选
  showSideScreen:function(){
    if(this.data.typeId.length <= 0){
      wx.showToast({
        title: '请选择酒分类~',
        icon: 'none'
      })
    }else{
      if((this.data.brandListData.length > 0 && this.data.brandListData[0].childrens.length > 0) || this.data.screenListData.length > 0){
        this.setData({
          isSideScreenShow: true
        })
      }else{
        wx.showToast({
          title: '抱歉，该商品分类还未设置筛选条件,无法进行筛选~',
          icon: 'none'
        })
      }
    }
  },
  // 关闭侧边筛选
  hiddenSideScreen:function(){
    this.setData({
      isSideScreenShow: false
    })
  },
  // 品牌展开
  setBrandStyle:function(e){
    let brandId = e.currentTarget.dataset.brandid;
    let brandStyle = e.currentTarget.dataset.style;
    let newBrandStyle = '';
    if(brandStyle == 'up'){
      newBrandStyle = 'down';
    }else{
      newBrandStyle = 'up'
    }
    this.setData({
      brandStyleId: brandId,
      brandStyle: newBrandStyle
    })
  },
  // 品牌选择
  chooseBrand:function(e){
    let brandId = e.currentTarget.dataset.brandid;
    let brandListData = this.data.brandListData;
    let screen = this.data.screen;
    brandListData.forEach(item => {
      item.childrens.forEach(node => {
        if(node.brand_id == brandId){
          node.choose = true
        }else{
          node.choose = false
        }
      })
    })
    this.setData({
      brandListData
    })
  },
  // 筛选展开
  setScreenStyle:function(e){
    let screenId = e.currentTarget.dataset.id;
    let screenListData = this.data.screenListData
    screenListData.forEach(item => {
      if(item.id == screenId){
        if(item.choose == true){
          item.choose = false;
        }else{
          item.choose = true;
        }
      }
    })
    this.setData({
      screenListData
    })
  },
  // 筛选品牌检索
  brandSearchChoose:function(e){
    this.setData({
      brandSearch: e.currentTarget.dataset.value,
    })
  },
  // 筛选条件选择
  chooseScreen:function(e){
    let nowItem = e.currentTarget.dataset.item;
    let screenListData = this.data.screenListData;
    screenListData.forEach(item => {
      item.condition_item.forEach(node => {
        if(nowItem.id == node.id){
          if(node.choose == true){
            node.choose = false;
          }else{
            node.choose = true;
          }
        }
      })
    })
    this.setData({
      screenListData
    })
  },
  // 重置筛选条件
  resetScreen:function(){
    let screenListData = this.data.screenListData;
    let brandListData = this.data.brandListData;
    screenListData.forEach(item => {
      item.condition_item.forEach(node => {
        node.choose = false;
      })
    })
    brandListData.forEach(item => {
      item.childrens.forEach(node => {
        node.choose = false;
      })
    })
    this.setData({
      screenListData,
      brandListData,
      'screen.brand_id':null,
      'screen.condition_item_id': []
    })
  },
  // 筛选确认
  screenSubmit:function(){
    let screenListData = this.data.screenListData;
    let brandListData = this.data.brandListData;
    let screen = this.data.screen;
    screen.condition_item_id = [];
    screen.brand_id = null;
    
    screenListData.forEach(item => {
      item.condition_item.forEach(node => {
        if(node.choose == true){
          screen.condition_item_id.push(node.condition_item_id);
        }
      })
    })
    brandListData.forEach(item => {
      item.childrens.forEach(node => {
        if(node.choose == true){
          screen.brand_id = node.brand_id
        }
      })
    })
    
    if(screen.condition_item_id.length > 0 || screen.brand_id != null){
      this.setData({
        goodsList: [],
        screen,
        isSideScreenShow: false,
        'pagination.pageNum': 1
      })
      this.getGoodsListData(this.data.pagination,this.data.screen);
    }else{
      wx.showToast({
        title: '请选择筛选条件',
        icon: 'none'
      })
    }
    
  }
})